window.readDetail = new Vue({
    el: '#exerciseDetail',
    data() {
        return {
            second: 0,//
            time: '00:00:00',//做题时长
            interVal: '',//
            isFull: false,//是否全屏
            isPop: true,//顶部提示
            isPlay: false,//是否在播放中
            audio: '',//音频对象
            isOriginal: true,//是否显示原文
            current: 0,//当前正在看的题目
            left: '',//
            display: 'none',//

            dataQuestion: '', //json数据
            content_id: '',//当前整套题目content_id
            content_btn: '',//当前小题目content_id
            content_btn_status: '',//当前小题目 方形 圆形
            content_pid: '',//当前题目pid
            letterArry: [], //序号  26个字母
            AnswerArry: [], //通用答案数组
            confirmPop: false,//交卷提示
            doLength: 0,//已经做了多少题
        }
    },
    created() {
        let that = this;
        //初始获取数据
        that.getData();
        for (var i = 65; i < 91; i++) {
            that.letterArry.push(String.fromCharCode(i));
        }
        let clock = sessionStorage.getItem('listenTime' + $('#content_id').val());
        if (clock) {
            that.time = that.formateSeconds(clock);
            that.second = clock;
        }
        that.$nextTick(function () {
            //做题时长
            that.interVal = setInterval(function () {
                that.second++;
                that.time = that.formateSeconds(that.second);
                sessionStorage.setItem('listenTime' + $('#content_id').val(), that.second);
            }, 1000);
        });

    },
    mounted() {
        let that = this;
        that.$nextTick(function () {
            //初始化音频
            that.audio = $('#bgAudio')[0];
            that.addListen();
            // 声音拖拽大小
            $("#dragVolum").draggable({
                    containment: "parent",
                    axis: "x",
                    drag: function () {
                        that.audio.volume = parseInt(($('#dragVolum')[0].style.left)) * 0.008;
                    },
                }
            );

        });
    },
    beforeDestroy() {
    },
    destroyed() {
    },
    methods: {

        //获取初始数据
        getData() {
            let that = this;
            $.get('/cn/exercise/listen-exercise', {
                content_id: $('#content_id').val(),
            }, function (res) {
                if (res.code == 1) {
                    that.content_id = $('#content_id').val();
                    that.initData(res);
                } else {
                    alert(res.message)
                }
            }, 'json')
        },
        //初始化做题数据处理
        initData(data) {
            let that = this;
            that.dataQuestion = data;
            that.dataQuestion.topic.map((train, index) => {
                let arry = [];
                that.AnswerArry.push(arry);
                if (train.parent.type == 2) { //单选题
                    train.son.map((trainSon, indexSon) => {
                        let obj = {};
                        obj.content_id = trainSon.content_id;
                        obj.answer = '';
                        obj.trueAnswer = trainSon.alternatives;
                        that.AnswerArry[index].push(obj);
                    });
                } else if (train.parent.type == 3) { //多选题
                    train.son.map((trainSon, indexSon) => {
                        let obj = {};
                        obj.content_id = trainSon.content_id;
                        obj.answer = [];
                        obj.trueAnswer = trainSon.alternatives;
                        that.AnswerArry[index].push(obj);
                    });
                } else if (train.parent.type == 1 || train.parent.type == 5 || train.parent.type == 4) { //除开单选多选 都按填空处理
                    train.parent.description = train.parent.description.replace(/#&/g, '#&*');
                    train.parent.description = train.parent.description.split('*');

                    let last = train.parent.description[train.parent.description.length - 1];
                    train.parent.description = train.parent.description.slice(0, train.parent.description.length - 1);

                    if (train.parent.type == 1) { //表格填空
                        for (var i in train.parent.description) {
                            train.parent.description[i] = train.parent.description[i].replace(/#&/g,
                                "<input type='text' placeholder='" + train.son[i].qNum + "' data-topicNum='" + index + "' data-content-id='" + train.son[i].content_id +
                                "' data-sonNum='" + i + "' class='BlankInput BlankInput1' oninput='window.readDetail.blackBlur(this)' onclick='window.readDetail.getDoNow(" + train.son[i].content_id + ")' id='listen_" + train.son[i].content_id + "'>");
                        }
                        let str = '';
                        for (var i in train.parent.description) {
                            str += train.parent.description[i];
                        }
                        train.parent.description = str + last;
                        train.son.map((trainSon, indexSon) => {
                            let obj = {};
                            obj.content_id = trainSon.content_id;
                            obj.answer = '';
                            obj.trueAnswer = trainSon.alternatives;
                            that.AnswerArry[index].push(obj);
                        });
                    } else if (train.parent.type == 5) { //图片填空
                        train.parent.image = 'https://ielts.thinkwithu.com' + train.parent.image;
                        for (var i in train.parent.description) {
                            train.parent.description[i] = train.parent.description[i].replace(/#&/g, "" +
                                "<input type='text' placeholder='" + train.son[i].qNum + "' class='BlankInput' data-topicNum='" + index + "' data-content-id='" + train.son[i].content_id +
                                "' data-sonNum='" + i + "' id='listen_" + train.son[i].content_id + "' onclick='window.readDetail.getDoNow(" + train.son[i].content_id + ")'  oninput='window.readDetail.blackBlur(this)'>");
                        }
                        train.son.map((trainSon, indexSon) => {
                            let obj = {};
                            obj.content_id = trainSon.content_id;
                            obj.answer = '';
                            obj.trueAnswer = trainSon.alternatives;
                            that.AnswerArry[index].push(obj);
                        });
                    } else if (train.parent.type == 4 && train.parent.questionType != 2) { //配对填空题  算一题情况
                        for (var i in train.parent.description) {
                            train.parent.description[i] = train.parent.description[i].replace(/#&/g, "" +
                                "<input type='text' placeholder='' class='BlankInput pairInput' data-topicNum='" + index + "' data-content-id='" + train.son[0].content_id +
                                "' data-sonNum='" + i + "' id='listen_" + train.son[0].content_id + "' onclick='window.readDetail.getDoNow(" + train.son[0].content_id + ")'  oninput='window.readDetail.blackMatch(this)'>");
                        }
                        train.son.map((trainSon, indexSon) => {
                            let obj = {};
                            obj.content_id = trainSon.content_id;
                            obj.answer = '';
                            obj.trueAnswer = trainSon.alternatives;
                            that.AnswerArry[index].push(obj);
                        });
                    } else if (train.parent.type == 4 && train.parent.questionType == 2) { //配对填空题  算多道题题情况
                        for (var i in train.parent.description) {
                            train.parent.description[i] = train.parent.description[i].replace(/#&/g, "" +
                                "<input type='text' placeholder='' class='BlankInput pairInput' data-topicNum='" + index + "' data-content-id='" + train.son[i].content_id +
                                "' data-sonNum='" + i + "' id='listen_" + train.son[i].content_id + "' onclick='window.readDetail.getDoNow(" + train.son[i].content_id + ")'  oninput='window.readDetail.blackMatchMore(this)'>");
                        }
                        train.son.map((trainSon, indexSon) => {
                            let obj = {};
                            obj.content_id = trainSon.content_id;
                            obj.answer = '';
                            obj.trueAnswer = trainSon.alternatives;
                            that.AnswerArry[index].push(obj);
                        });
                    }

                }
            });
            console.log(that.AnswerArry)
        },

        //review 题目
        reviewStatus() {
            let that = this;
            $.get('/cn/exercise/review-speak', {
                pid: that.content_pid,
                content_id: that.content_btn,
                type: that.content_btn_status == 0 ? '1' : '2',//1 圆形 2方形
            }, function (res) {
                if (res.code == 1) {
                    that.dataQuestion.question_list.map(item => {
                        if (item.content_id == that.content_btn) {
                            that.content_btn_status == 0 ? item.status = 1 : item.status = 0;
                        }
                    })
                }
            }, 'json')
        },
        blackMatch(obj) {//配对填空题  只算一题情况
            let that = this;
            let str = '';
            $('.pairInput').each(function () {
                if ($(this).val().replace(/\s*/g, "") == '') {
                    str += '*';
                } else {
                    str += $(this).val();
                }
            });
            let site = $(obj).attr('data-topicNum');
            that.AnswerArry[site][0].answer = str;
            that.getAnswer();
        },
        blackMatchMore(obj) {//配对填空题  多题情况
            let that = this;
            let str = '';
            if ($(obj).val().replace(/\s*/g, "") == '') {
                str = '*';
            } else {
                str = $(obj).val();
            }
            let site = $(obj).attr('data-topicNum');
            let siteDetail = $(obj).attr('data-sonNum');
            that.AnswerArry[site][siteDetail].answer = str;
            that.getAnswer();
        },
        //图片填空题
        blackBlur(obj) {
            let that = this;
            let site = $(obj).attr('data-topicNum');
            let queIndex = $(obj).attr('data-sonNum');
            that.AnswerArry[site][queIndex].answer = $(obj).val();
            that.getAnswer();
        },
        //监听双向绑定的数据的变化 判断是否做了 多选判断length 单选填空判断去除空格为空
        getAnswer(site, id, index, answerCount) {
            let that = this;
            this.AnswerArry.map(item => {
                item.map(itemSon => {
                    that.dataQuestion.question_list.map((listItem, index) => {
                        if (typeof itemSon.answer == 'string') {
                            if (listItem.content_id == itemSon.content_id && itemSon.answer.replace(/\s*/g, '') != '') {
                                listItem.isDo = 1;
                            } else if (listItem.content_id == itemSon.content_id && itemSon.answer.replace(/\s*/g, '') == '') {
                                listItem.isDo = 0;
                            }
                        } else {
                            if (listItem.content_id == itemSon.content_id && itemSon.answer.length != 0) {
                                listItem.isDo = 1;
                                if (answerCount && (itemSon.answer.length > answerCount)) {
                                    itemSon.answer = itemSon.answer.splice(itemSon.answer.length - answerCount, itemSon.answer.length)
                                }
                                itemSon.answer = itemSon.answer.sort()
                            } else if (listItem.content_id == itemSon.content_id && itemSon.answer.length == 0) {
                                listItem.isDo = 0;
                            }
                        }
                    })
                })
            });
            console.log(that.AnswerArry);
        },
        //当前
        getDoNow(content_id) {
            let that = this;
            that.dataQuestion.question_list.map((item, index) => {
                if (item.content_id == content_id) {
                    that.current = index;
                    that.content_btn = content_id;
                }
            })
        },
        //上一题
        prev() {
            let that = this;
            if (that.current > 0) {
                that.current = that.current - 1;
                that.dataQuestion.question_list.map((item, index) => {
                    if (index == that.current) {
                        that.content_btn = item.content_id;
                        document.getElementById('listen_' + that.content_btn).scrollIntoView({
                            block: "center",
                            behavior: "smooth"
                        })
                    }
                })
            }
        },
        //下一题
        next() {
            let that = this;
            if (that.current < that.dataQuestion.question_list.length - 1) {
                that.current = parseInt(that.current) + 1;
                that.dataQuestion.question_list.map((item, index) => {
                    if (index == that.current) {
                        that.content_btn = item.content_id;
                        document.getElementById('listen_' + that.content_btn).scrollIntoView({
                            block: "center",
                            behavior: "smooth"
                        })
                    }
                })
            }
            console.log(that.current)
        },
        //按钮点击滚动
        welter(pid, content_id, index, status) {
            this.current = index;//当前正在看的题目
            this.content_btn_status = status;//当前正在看的题目的状态  0方形 1 圆形
            console.log(content_id);
            this.content_btn = content_id;
            this.content_pid = pid;
            document.getElementById('listen_' + content_id).scrollIntoView({block: "center", behavior: "smooth"})
        },
        //浮窗跟随
        followIn(e) {
            let that = this;
            let left = $(e.target).offset().left - $(e.target).parent().offset().left;//子元素在父元素中的偏移量
            that.left = left;
            that.display = 'flex';
        },
        followOut(e) {
            let that = this;
            that.left = '';
            that.display = 'none';
        },
        //展开折叠
        toggle(e) {
            if ($(e.target).hasClass('spinOut')) {
                $(e.target).removeClass('spinOut');
            } else {
                $(e.target).addClass('spinOut');
            }
            $(e.target).parents('.ItemIn').find('.singleZt').slideToggle();
        },
        //提交前做数据处理
        processData() {
            let that = this;
            that.doLength = 0;//每次点开重新计算已做题数
            that.dataQuestion.question_list.map(item => {
                if (item.isDo == 1) {
                    that.doLength++;
                }
            });
            that.confirmPop = true
        },
        //提交数据
        submitText() {
            let that = this;
            let answer = [];
            this.AnswerArry.map(item => {
                item.map(itemSon => {
                    let obj = {};
                    obj.content_id = itemSon.content_id;
                    if (typeof itemSon.answer == 'string') {
                        obj.answer = itemSon.answer;
                    } else {
                        obj.answer = itemSon.answer.sort().toString().replaceAll(',', '');
                    }
                    obj.trueAnswer = itemSon.trueAnswer;
                    answer.push(obj)
                })
            });
            $.post('/cn/exercise/save-listen-read-answer', {
                cate_id: that.dataQuestion.article.cate_id,
                resultid: that.dataQuestion.resultid,
                newid: that.dataQuestion.newid,
                answer: answer,
                typeid: '1',//1听力2阅读
                time: that.second,
            }, function (res) {
                if (res.code == 1) {
                    window.location.href = '/cn/exercise/listen-review?content_id=' + that.dataQuestion.article.content_id
                } else {
                    alert(res.message)
                }
            }, 'json')
        },
        //当前做题 滚动 跟随


        //音频事件监听
        addListen() {
            let that = this;
            that.audio.addEventListener("canplay", function () {
                that.audio.play();
                that.audio.volume = 0.7;
            });
            that.audio.addEventListener("play", function () {

            });
            that.audio.addEventListener("playing", function () {
                that.isPlay = true;
            });
            that.audio.addEventListener("pause", function () {

            });
            that.audio.addEventListener("ended", function () {
                that.isPlay = false;
            });
        },
        //  播放/暂停音频
        playAudio() {
            let that = this;
            if (!that.isPlay) {
                that.audio.play();
            } else {
                that.audio.pause();
            }
            that.isPlay = !that.isPlay
        },
        //  全屏、退出全屏
        launchFullscreen() {
            let that = this;
            let element = document.documentElement;
            if (!that.isFull) {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                }
                that.isFull = true;
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
                that.isFull = false;
            }
        },
        //时间转换
        formateSeconds(endTime) {
            let secondTime = parseInt(endTime);//将传入的秒的值转化为Number
            let min = 0;// 初始化分
            let h = 0;// 初始化小时
            let result = '';
            if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
                min = parseInt(secondTime / 60);//获取分钟，除以60取整数，得到整数分钟
                secondTime = parseInt(secondTime % 60);//获取秒数，秒数取佘，得到整数秒数
                if (min > 60) {//如果分钟大于60，将分钟转换成小时
                    h = parseInt(min / 60);//获取小时，获取分钟除以60，得到整数小时
                    min = parseInt(min % 60);//获取小时后取佘的分，获取分钟除以60取佘的分
                }
            }
            result = `${h.toString().padStart(2, '00')}:${min.toString().padStart(2, '00')}:${secondTime.toString().padStart(2, '00')}`;
            return result;
        }
    }
});
